﻿using CTP.CRM.Core.Logging;
using CTP.CRM.Core.Logger;
using LogLevel = CTP.CRM.Core.Logger.LogLevel;

namespace CTP.CRM.Core.Configuration
{
    //
    // 摘要:
    //     主机配置处理器，在 Host 启动前，拦截配置注入服务并进行自定义加载配置逻辑
    public static class ConfigurationHostBuilderExtensions
    {
        public static WebApplicationBuilder AddConfigurationContainer(this WebApplicationBuilder webBuilder)
        {
            ConfigurationManager mainConfiguration = webBuilder.Configuration;
            Action<IConfigurationBuilder> configureDelegate;
            if (mainConfiguration.GetValue<bool>("Configuration:UseLocalConfiguration"))
            {
                Console.WriteLine("-- 启用本地配置文件");
                configureDelegate = delegate (IConfigurationBuilder builder)
                {
                    string path = mainConfiguration["Configuration:ConfiguraFileName"];
                    builder.AddJsonFile(path, optional: false, reloadOnChange: true);
                };
            }
            else
            {
                Console.WriteLine("-- 启用配置中心");
                configureDelegate = delegate (IConfigurationBuilder builder)
                {
                    Console.WriteLine("-- 开始连接配置中心");
                    LogManager.UseConsoleLogging(LogLevel.Info);
                    // builder.AddApollo(mainConfiguration.GetSection("Configuration:Apollo")).AddNamespace(mainConfiguration["Configuration:Apollo:Namespace"], ConfigFileFormat.Json);
                    Console.WriteLine("-- 连接成功");
                };
            }

            webBuilder.Host.ConfigureAppConfiguration(configureDelegate);
            return webBuilder;
        }
    }
}
